//tslint:disable
import { Component, OnInit, Input } from '@angular/core';
import { ActionSheetController, AlertController } from "@ionic/angular";
import { Subscription } from 'rxjs';
import { AppGlobalService } from 'src/app/shared/service/app-global.service';
import { HttpService } from 'src/app/shared/service/http.service';
import { MessageService } from 'src/app/shared/service/message.service';
import { EventService } from 'src/app/shared/service/event.service';
import { ModalController } from '@ionic/angular';
import { RemarksContentComponent } from '../remarks-content/remarks-content.component';
import { SharePageComponent } from '../share-page/share-page.component';
import { ActionSheetService, Modal, ModalService } from 'ng-zorro-antd-mobile';
import { RecommendModalComponent } from '../recommend-modal/recommend-modal.component';
import { ServiceModuleComponent } from '../service-module/service-module.component';
import { ModalFromCenterLeave, ModalFromCenterEnter } from 'src/app/utils/transitions';
import { PageModalService } from 'src/app/shared/service/page-modal-service';
@Component({
  selector: 'app-performance-info-list',
  templateUrl: './performance-info-list.component.html',
  styleUrls: ['./performance-info-list.component.scss'],
})
export class PerformanceInfoListComponent implements OnInit {
  @Input() tagData: any;
  pageNo = 1;
  pageSize: number;
  pageTotal: number;
  tempEvent: any;
  // 筛选及页面数据参数
  params: any = { content: {} };
  sessionId: string;
  moreSelect = false;
  recommendeIds: any;
  tempItem: any;
  listData: any;
  dataIndex: any;
  phoneArray = [];
  icons = [];
  showLoadMore = false;
  listenerName: any;
  constructor(
    private appGlobalService: AppGlobalService,
    private httpService: HttpService,
    private message: MessageService,
    private actionSheetCtrl: ActionSheetController,
    private actionSheet: ActionSheetService, // 必须有
    private alertController: AlertController,
    private eventService: EventService,
    public modalController: ModalController,
    public pageModalService : PageModalService,
  ) {

    //1.9.0 维保 最新改动版本 检查列表是否有多次请求的情况 有的话就取最新的
    if (this.eventService.eventEmit.listenerCount(this.listenerName) > 0) {
      this.eventService.removeCustomListListenersByName(this.listenerName);
    }

    this.eventService.eventEmit.on(this.listenerName, (obj) => {
      this.refreshListData(obj);
    });

    this.eventService.eventEmit.on('performanceInfoTagAskForList', res => {
      const ids = [];
      this.listData.forEach(element => {
        if (element.checked) {
          ids.push(element[this.tagData.data.chooseSubmit.formKey]);
        }
      });
      if (ids.length > 0) {
        this.moreSelect = true;
        this.recommendeIds = ids.join(',');
        this.presentModal({
          minLength: 5,
          maxLength: 50,
          value: '',
          placeHolder: '请填写推荐说明，说明将展示给推荐客户',
          button: '确定'
        });

      }

    });

    this.eventService.eventEmit.on('performanceInfoListTagAskForList', res => {
      this.refreshListData(res);
    });
    // 全选
    this.eventService.eventEmit.on('recommendCheckedAll', res => {
      if (res) {
        this.listData.forEach(element => {
          element.checked = true;
        });
      } else {
        this.listData.forEach(element => {
          element.checked = false;
        });
      }
    });
  }

  refreshListData(param) {
    const that = this;
    if (param === undefined) {
      return;
    }
    this.pageNo = 1;
    if (!param.showName) {
      if (this.tagData.data.submit && this.tagData.data.submit.content) {
        param.showName = this.tagData.data.submit.content.showName;
      }
    }
    this.params.content = param;
    if (param.filter.endDate && param.filter.startDate) {
      that.params.content["endDate"] = param.filter.endDate;
      that.params.content["startDate"] = param.filter.startDate;
    }
    this.params.id = this.tagData.data.submit.id;
    this.params.content.pageNo = this.pageNo;
    this.params.sessionId = localStorage.getItem("sessionId");
    this.httpService.post('application/submit', this.params, res => {
      if (res.success) {
        if (res.data.submit) {
          this.params = res.data.submit; // 为了每次刷新下一页的参数 "oldIndex"
        }
        this.tagData.data.data = [];
        const result = res.data.data; // JSON.parse(res.data.data);
        this.tagData.data.data = result;
        this.listData = this.tagData.data.data;
        this.tagData.data = res.data;
        if (res.data.moreButton) {
          this.tagData.data.moreButton = res.data.moreButton;
        }
        this.pageTotal = this.tagData.pageTotal;
        this.showLoadMore = !this.tagData.data.moreButton && this.tagData.data.submit && this.pageTotal && (this.pageNo < Math.ceil(this.pageTotal / this.pageSize)) && this.tagData.asyncShow !== 'true';
      }
    },
      err => {
        // 请求数据失败
        this.tagData.data.data = [];
        // this.appGlobalService.showToast(err.message, 2000, 'middle');
      });
  }



  ngOnInit() {
    // console.log(this.tagData);
    this.sessionId = localStorage.getItem('sessionId');
    if (this.tagData.data.submit !== undefined) {
      this.params = this.tagData.data.submit;
    }
    this.params.sessionId = this.sessionId;
    this.listData = this.tagData.data.data;
    this.pageSize = this.tagData.pageSize;
    this.pageTotal = this.tagData.pageTotal;
    this.listenerName = this.tagData.name + 'AskForList';

  }

  async presentAction() {
    const buttonsArr = [
      {
        text: "取消",
        cssClass: ["action-sheet-font-color", "action-sheet-font-top"],
        handler: () => {
          actionSheet.dismiss();
        }
      }
    ];
    if (this.phoneArray[1]) {
      buttonsArr.unshift({
        text: this.phoneArray[1],
        cssClass: ["action-sheet-font-color"],
        handler: () => {
          this.presentAlertConfirm(Number(this.phoneArray[1]));
        }
      });
    }

    if (this.phoneArray[0]) {
      buttonsArr.unshift({
        text: this.phoneArray[0],
        cssClass: ["action-sheet-font-color"],
        handler: () => {
          this.presentAlertConfirm(this.phoneArray[0]);
        }
      });
    }

    const actionSheet = await this.actionSheetCtrl.create({
      mode: "md",
      cssClass: "match-padding",
      buttons: buttonsArr
    });
    await actionSheet.present();
  }

  async presentAlertConfirm(mobile, name?) {
    const msg = (name ? name + ' ' : '') + mobile;
    const alert = await this.alertController.create({
      header: this.tagData.nickName,
      message: msg,
      buttons: [
        {
          text: "取消",
          role: "cancel",
          cssClass: "secondary"
        },
        {
          text: "拨打",
          handler: () => {
            this.httpService.changeCallNumber(mobile);
          }
        }
      ]
    });

    await alert.present();
  }


  // 分享弹框
  async presentShareModal(shareData) {
    const modal = await this.modalController.create({
      showBackdrop: true,
      cssClass: 'sharePage',
      backdropDismiss: true,
      component: SharePageComponent,
      componentProps: { tagData: shareData }
    });
    await modal.present();
    // 监听销毁的事件
    const modalData = await modal.onDidDismiss(); // 获取关闭传回的值
    console.log(modalData);
  }
  iconClick(item, dataIndex?) {
    if (dataIndex >= 0) {
      this.dataIndex = dataIndex;
    }

    if (item.modelType === "iconLink") {
      if (item.link.type && item.link.type === 'chat') {//
        this.httpService.gotoChat(item);
      } else if (item.label === '分享') {
        const params = {
          sessionId: localStorage.getItem("sessionId"),
          pageId: item.link.target,
          params: item.link.params
        };
        this.httpService.post('application/page', params, res => {
          console.log(JSON.parse(res.script));
          const tmpShareData = JSON.parse(res.script).views[0].tags[0].data;
          // console.log(tmpShareData);
          this.presentShareModal(tmpShareData);
        });
      } else {
        // 修改
        const params = {
          pageId: item.link.target,
          params: item.link.params,
          sessionId: localStorage.getItem("sessionId")
        };
        this.appGlobalService.goToForward(params);
      }
    }
    if (item.modelType === "iconSubmit") {
      const params = {
        content: item.submit.content,
        id: item.submit.id,
        sessionId: localStorage.getItem("sessionId")
      };
      this.httpService.post("application/submit", params, res => {
        this.appGlobalService.showToast(res.message, 1500, "middle");
        if (res.success) {
          this.appGlobalService.reloadCurrentPage();
          if (item.link && item.link.target) {
            const pageParams = {
              pageId: item.link.target,
              params: item.link.params ? item.link.params : {},
              sessionId: localStorage.getItem("sessionId")
            };
            this.appGlobalService.goToForward(pageParams);
          }
        }
      });
    }

    if (item.modelType === 'iconDelete') {
      // 删除
      const params = {
        content: item.submit.content,
        id: item.submit.id,
        sessionId: localStorage.getItem("sessionId")
      };
      this.httpService.post("application/submit", params, res => {
        this.appGlobalService.showToast(res.message, 1500, "middle");
        if (res.success) {
          if (this.dataIndex >= 0 && this.dataIndex < this.tagData.data.data.length) {
            this.tagData.data.data.splice(this.dataIndex, 1);
          }
        }
      });
    }
    if (item.modelType === "phone") {
      // 电话
      this.phoneArray = item.phone.split(",");
      if (this.phoneArray.length > 1) {
        this.presentAction();
      } else {
        this.presentAlertConfirm(Number(this.phoneArray[0]), item.label);
      }
    }
    if (item.modelType === "dialog") {
      // 备注
      // this.remarksIcon = item;
      // this.openRemarks = true;
      this.presentModal2("remarks", item);
    }
    // 商铺列表新增类型
    if (item.modelType === 'pageDialog') {
      this.openTipsPageModal("recommend-modal", item);
    }
    // 新增两个components类型
    if (item.modelType === "remarkList") {
      // tslint:disable-next-line:max-line-length
      // const moreObj = JSON.parse('{"layout":"right","data":[{"submit":{"id":"refresh","content":{"opportunity_id":"5eb3aed42872fb0001f76ed7"}},"action":"submit","label":"刷新","paramName":"opportunity_id"},{"link":{"type":"page","params":{"opportunity_id":"5eb3aed42872fb0001f76ed7"},"target":144348},"action":"link","label":"修改"}],"icon":"nav_icon_more@3x.png"}');
      if (item.listRemark) {
        // this.remarkList(item);
      }
    }
    if (item.modelType === "serviceModal") {
      this.openSeviceModal("sevice-modal", item);
    }
    if (item.modelType === "childIconLink") {
      if (item.childIconList) {
        // this.remarkList(item);
      }
    }
  }

  // 单选 推荐
  recommentAction(item) {
    this.moreSelect = false;
    this.tempItem = item;
    this.recommendeIds = item[this.tagData.data.chooseSubmit.formKey];
    this.presentModal({ minLength: '5', maxLength: '50', value: '', placeHolder: '请填写推荐说明，说明将展示给推荐客户', button: '确定' });
  }

  recommentPhoneAction(phone) {
    this.httpService.changeCallNumber(phone);
  }


  async presentModal(textarea) {
    console.log("item", textarea);
    const modal = await this.modalController.create({
      showBackdrop: true,
      // backdropDismiss: false,
      cssClass: 'remarks',
      component: RemarksContentComponent,
      componentProps: { textarea, type: 'textarea' }
    });
    await modal.present();
    // 监听销毁的事件
    const modalData = await modal.onDidDismiss(); // 获取关闭传回的值
    console.log(modalData, "moddddddd");
    if (!modalData.data) {
      return;
    }
    this.recommendWithRemark(modalData.data.value);
  }

  async presentModal2(value, item) {
    console.log("item", item);
    const modal = await this.modalController.create({
      showBackdrop: true,
      cssClass: value,
      component: RemarksContentComponent,
      componentProps: { item, type: value }
    });
    await modal.present();
    // 监听销毁的事件
    const modalData = await modal.onDidDismiss(); // 获取关闭传回的值
    console.log(modalData, "moddddddd");
  }
  async openTipsPageModal(className, item: any) {
    try {
      const params = {
        sessionId: localStorage.getItem("sessionId"),
        pageId: item.link.target,
        params: item.link.params
      };
      this.httpService.post('application/page', params, async res => {
        const tagData = JSON.parse(res.script).views[0].tags[0].data;
        if (tagData) {
          const modal = await this.modalController.create({
            showBackdrop: true,
            cssClass: className,
            animated: false,
            component: RecommendModalComponent,
            componentProps: { tagData },
            leaveAnimation: ModalFromCenterLeave,
            enterAnimation: ModalFromCenterEnter

          });
          await modal.present();
          const modalData = await modal.onDidDismiss().then((data) => {
            this.appGlobalService.reloadCurrentPage();
          }); // 获取关闭传回的值
        }
      });
    } catch (error) {
      console.log('error----->' + JSON.stringify(error));
    }
  }

  async openSeviceModal(className, item) {
    const type = {
      "sevice-modal": ServiceModuleComponent,
    };
    const modal = await this.modalController.create({
      showBackdrop: true,
      cssClass: className,
      component: type[className],
      componentProps: { tagData: item }
    });
    await modal.present();
    // 监听销毁的事件
    const modalData = await modal.onDidDismiss(); // 获取关闭传回的值
  }
  recommendWithRemark(value) {
    if (value.length < 1) {
      return;
    }
    const params = {
      sessionId: this.sessionId,
      content: this.tagData.data.chooseSubmit.content,
      id: this.tagData.data.chooseSubmit.id,
    };
    params.content[this.tagData.data.chooseSubmit.formKey] = this.recommendeIds;
    params.content.remark = value;
    this.httpService.post('application/submit', params, res => {
      if (res.success) {
        if (this.tagData.data.chooseSubmit.link && this.tagData.data.chooseSubmit.link.target.length > 0) {
          this.appGlobalService.openPage(this.tagData.data.chooseSubmit.link);
        } else {
          this.appGlobalService.showToast(res.message, 1500, 'middle');
          if (this.moreSelect) {
            this.listData.forEach(element => {
              if (element.checked) {
                element.fourthRowLeft.firstText.label = "刚刚已推荐";
              }
            });
          } else {
            this.tempItem.fourthRowLeft.firstText.label = "刚刚已推荐";
          }
        }

      } else {
        this.appGlobalService.showToast(res.message ? res.message : '推荐失败', 1500, 'middle');
        if (res.message && res.message === '推荐说明含有非法词') {
          this.presentModal({ minLength: 5, maxLength: 50, value, placeHolder: '请填写推荐说明，说明将展示给推荐客户', button: '确定' });
        }
      }

    });
  }

  choose(item) {
    item.checked = !item.checked;
    this.checkAll();
  }
  // 检查是否已经全选
  checkAll() {
    // max 10
    if (this.tagData.data.chooseSubmit && this.tagData.data.chooseSubmit.type && this.tagData.data.chooseSubmit.type === 'ljpopup') {
      this.tagData.data.chooseSubmit.maxRow = this.tagData.data.chooseSubmit.maxRow > 0 ? this.tagData.data.chooseSubmit.maxRow : 10;
      let count = 0;
      this.listData.forEach(element => {
        if (element.checked) {
          ++count;
          if (count > this.tagData.data.chooseSubmit.maxRow) {
            element.checked = false;
            this.appGlobalService.showToast('最多只能选择' + this.tagData.data.chooseSubmit.maxRow + '个', 2000, 'middle');
          }
        }
      });
    } else {
      let all = true;
      this.listData.forEach(element => {
        if (!element.checked) {
          all = false;
        }
      });
      this.eventService.eventEmit.emit('recommendAllResult', all);
    }

  }
  detailPage(link) {
    if (!link) {
      return;
    }
    const pageParams = {
      pageId: link.target,
      params: link.params,
      sessionId: localStorage.getItem('sessionId')
    };
    this.appGlobalService.goToForward(pageParams);
  }

  async call(e, mobile, name) {
    e.stopPropagation();
    const msg = (name ? name + ' ' : '') + mobile;
    const alert = await this.alertController.create({
      message: msg,
      buttons: [
        {
          text: "取消",
          role: "cancel",
          cssClass: "secondary"
        },
        {
          text: "拨打",
          handler: () => {
            this.httpService.changeCallNumber(mobile);
          }
        }
      ]
    });

    await alert.present();
  }

  loadMoreData(event) {
    try {
      this.tempEvent = event;
      // // 请求下一个页面
      this.pageNo = this.pageNo + 1;
      // // 参数
      this.params.content.pageNo = this.pageNo;
      // 请求获取新数据
      this.httpService.post('application/submit', this.params, res => {

        // 请求数据成功
        if (res.success) {
          const resList = res.data.data;
          // 追加返回数据
          if (resList && resList.length > 0) {
            // 追加数据
            resList.map(v => {
              this.listData.push(v);
            });
            this.checkAll();
          } else {
            event.target.disabled = true;
          }
        } else {
          // 请求失败，更新当前页数
          this.pageNo = this.pageNo - 1;
          // 请求数据失败
          this.appGlobalService.showToast(res.message, 2000, 'middle');
        }
        event.target.complete();

      }, err => {
        // 请求失败，更新当前页数
        this.pageNo = this.pageNo - 1;
        // 请求数据失败
        this.appGlobalService.showToast(err.message, 2000, 'middle');
        event.target.complete();

      });
    } catch (error) {
      console.log('error----->' + JSON.stringify(error));
      event.target.complete();

    }
  }

  openPage(item, e){
    e.stopPropagation();
    if(item && item.link){
      this.pageModalService.openPage(item.link);
    }
  }

  ngOnDestroy(): void {
    this.eventService.eventEmit.removeListener(this.listenerName);
    this.eventService.eventEmit.removeListener('performanceInfoTagAskForList');
    this.eventService.eventEmit.removeListener('performanceInfoListTagAskForList');
  }
}
